package com.bridge.client.bridgedynamcclient.controller;

import com.bridge.client.bridgedynamcclient.consts.Const;
import com.bridge.client.bridgedynamcclient.utils.FXMLUtil;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Pagination;
import javafx.scene.layout.AnchorPane;
import javafx.util.Callback;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class BridgeRecordListController extends BaseController implements Initializable {

    @FXML
    private Pagination pageRecord;

    private Long firstRecordId;

    private Map<Integer,AnchorPane> pageCache=new HashMap<>();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initListener();
    }

    private void initListener() {
        initPage();
    }

    private void initPage() {

        pageRecord.setPageCount(1);
        pageRecord.setCurrentPageIndex(0);
        pageRecord.setPageFactory(new Callback<Integer, Node>() {
            @Override
            public Node call(Integer pageIndex) {
                return createPage(pageIndex);
            }
        });

    }

    private Node createPage(Integer pageIndex) {
        AnchorPane load = pageCache.get(pageIndex);
        if(load!=null){
            logger.info("createPage 使用缓存");
            return load;
        }
        logger.info("createPage 新创建页面");
        FXMLLoader loader = FXMLUtil.getLoader(getClass(), "record-page-view.fxml");
        try {
            System.out.println("pageIndex load前 = " + pageIndex);
            load = loader.load();
            System.out.println("pageIndex load后 = " + pageIndex);
            RecordPageController controller = loader.getController();
            controller.setRoot(load);
            controller.setConfig(pageIndex,firstRecordId,this);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //pageCache.put(pageIndex,load);
        return load;
    }
    public void callbackFirstPage(Long firstRecordId,Long totalSize){
        this.firstRecordId=firstRecordId;
        pageRecord.setPageCount(getTotalPage(totalSize));
        System.out.println("callbackFirstPage firstRecordId = " + firstRecordId);
    }

    private int getTotalPage(Long totalSize){
        boolean hasRemainder=(totalSize % Const.pageSize)!=0;
        logger.info("getTotalPage--hasRemainder:"+hasRemainder);
        int page= (int) (totalSize/Const.pageSize);
        logger.info("getTotalPage--page:"+page);
        return hasRemainder? page+1:page;
    }
}
